package com.example.myapplication1.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.myapplication1.db.AppSqliteHelper;
import com.example.myapplication1.model.User;

import java.sql.SQLData;

public class UserDao {
    private AppSqliteHelper helper;
    private String tableName="user";

    public UserDao(Context context){
        helper=new AppSqliteHelper(context);
    }

    //根据账号和密码查询用户
    public User login(String account,String password){
        SQLiteDatabase db = helper.getReadableDatabase();
        User user=null;
        Cursor c= db.query(tableName,null,"name=? and password=?",new String[]{account,password},null,null,null,null);
        if(c!=null && c.getCount()>0){
            if(c.moveToNext()){
                user=new User();
                int Log=c.getColumnIndex("id");
                c.moveToFirst();
                int id=c.getInt(Log);
                user.setId(id);
                user.setAccount(account);
                user.setPassword(password);
                Log=c.getColumnIndex("phone");
                c.moveToFirst();
                String phone=c.getString(Log);
                user.setPhone(phone);
            }
        }
        return user;
    }

    //添加用户到表中
    public boolean insert(User bean){
        SQLiteDatabase db=helper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",bean.getAccount());
        values.put("password",bean.getPassword());
        values.put("phone",bean.getPhone());
        long insert=db.insert(tableName,null,values);

        return insert>0;
    }

    //根据账号和手机号查询用户密码
    public boolean isExistByAccountOrPhone(String account,String phone){
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor c= db.query(tableName,null,"name=? or phone=?",new String[]{account,phone},null,null,null,null);
        if(c!=null && c.getCount()>0){
            return c.moveToNext();
        }
        return false;
    }

    //根据账号和手机号查询是否存在用户
    public String queryPasswordByAccountAndPhone(String account,String phone){
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor c= db.query(tableName,null,"name=? and phone=?",new String[]{account,phone},null,null,null,null);
        if(c!=null && c.getCount()>0){
            int Log=c.getColumnIndex("password");
            c.moveToFirst();
            String password= c.getString(Log);
            return password;
        }
        return null;
    }
}
